<template>
    <div class="div_article">
        <div class="title">{{ $getBilingualText(obj[vm.title]) }}</div>
        <div class="aside list">
            <div class="aside_2 col-12 col-sm-6">
                <div class="aside_row">
                    <span class="tag ellipsis_1 mr-1" v-if="getTagText(obj[vm.tag])">{{ getTagText(obj[vm.tag]) }}</span>
                    <router-link :to="obj[vm.url]" v-if="obj[vm.source] && obj[vm.url]">
                        <span class="source">{{ $getBilingualText(obj[vm.source]) || obj[vm.source] }}</span>
                    </router-link>
                    <span class="time">{{ $formatDateTime(obj[vm.create_time], 'datetime') }}</span>
                </div>
                <div class="aside_row">
                    <div class="praise">
                        <span>{{ t('likes') }}：{{ obj[vm.praise_len] }}</span>
                    </div>
                    <div class="see">
                        <span>{{ t('clicks') }}：{{ obj[vm.hits] }}</span>
                    </div>
                </div>
            </div>

            <div class="btns_interact col-12 col-sm-6">
                <!-- 收藏按钮 -->
                <b-button v-if="this.$store.state.user.user_id" @click="add_collect()" variant="outline-info">
                    <b-icon v-if="check_collected" icon="heart-fill"/>
                    <b-icon v-else icon="heart"/>
                    <span>{{ t('favorite') }}</span>
                </b-button>
                <b-button v-else @click="$router.push('/account/login')" variant="outline-info">
                    <b-icon v-if="check_collected" icon="heart-fill"/>
                    <b-icon v-else icon="heart"/>
                    <span>{{ t('favorite') }}</span>
                </b-button>

                <!-- 点赞按钮 -->
                <b-button class="ml" variant="outline-info" @click="add_praise()">
                    <b-icon icon="hand-thumbs-up"/>
                    <span>{{ t('like') }}</span>
                </b-button>

            </div>
        </div>
        <div class="description">{{ $getBilingualText(obj[vm.description]) }}</div>
        <div v-html="$getBilingualText(obj[vm.content])" class="content"></div>
    </div>
</template>

<script>
    import mixinI18n from "@/mixins/i18n.js";

    export default {
        mixins: [mixinI18n],
        props: {
            obj: {
                type: Object,
                default: function () {
                    return {};
                },
            },
            vm: {
                type: Object,
                default: function () {
                    return {
                        img: "img",
                        tag: "tag",
                        url: "url",
                        title: "title",
                        source: "source",
                        description: "description",
                        content: "content",
                        create_time: "create_time",
                        hits: "hits",
                        praise_len: "praise_len",
                    };
                },
            },
        },
        data() {
            return {
                // 是否已点赞
                check_praised: false,
                // 是否已收藏
                check_collected: false,
            };
        },
        methods: {
            /**
             * 获取标签文本（处理可能包含拼接内容的tag字段）
             */
            getTagText(tagValue) {
                if (!tagValue) return '';
                
                // 如果tag包含JSON格式，解析它
                const parsed = this.$getBilingualText(tagValue);
                
                // 如果解析后的内容包含JSON字符串，尝试提取纯文本部分
                // 例如："Data Science Biomedical Research {"zh":"生物医学期刊","en":"Biomedical Journal"} 2025-02-15 11:30:00"
                // 需要提取出纯文本部分
                if (parsed && typeof parsed === 'string') {
                    // 检查是否包含JSON对象字符串
                    const jsonMatch = parsed.match(/\{[^}]*"zh"[^}]*"en"[^}]*\}/);
                    if (jsonMatch) {
                        // 提取JSON对象前的文本部分
                        const beforeJson = parsed.substring(0, parsed.indexOf(jsonMatch[0])).trim();
                        // 尝试解析JSON对象
                        try {
                            const jsonObj = JSON.parse(jsonMatch[0]);
                            const jsonText = this.$getBilingualText(jsonMatch[0]);
                            // 返回JSON对象前的文本 + JSON解析后的文本
                            return (beforeJson ? beforeJson + ' ' : '') + jsonText;
                        } catch (e) {
                            // 如果解析失败，移除JSON字符串部分
                            return parsed.replace(/\{[^}]*"zh"[^}]*"en"[^}]*\}/g, '').trim();
                        }
                    }
                    // 移除可能包含的时间戳格式（YYYY-MM-DD HH:MM:SS）
                    const timePattern = /\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}/g;
                    if (timePattern.test(parsed)) {
                        return parsed.replace(timePattern, '').trim();
                    }
                }
                
                return parsed || '';
            },
            /**
             * 获取点赞状态
             */
            get_praise() {
                var user_id = this.$store.state.user.user_id;
                var _this = this;
                // 获取点赞记录，检查status值
                this.$get("~/api/praise/get_obj?", {
                    source_table: "article",
                    source_field: "article_id",
                    source_id: this.obj.article_id,
                    user_id
                }, (res) => {
                    if (res.result && res.result.obj) {
                        var praise = res.result.obj;
                        // 根据status值判断是否已点赞（1为点赞，0为取消）
                        _this.check_praised = praise.status === 1;
                    } else {
                        // 没有记录，说明未点赞
                        _this.check_praised = false;
                    }
                })
            },
            /**
             * 切换点赞状态
             */
            add_praise() {
                var body = {
                    source_table: "article",
                    source_field: "article_id",
                    source_id: this.obj.article_id,
                    user_id: this.$store.state.user.user_id,
                };
                var _this = this;
                _this.obj.praise_len = parseInt(_this.obj.praise_len) || 0;
                
                // 先获取当前点赞记录
                this.$get("~/api/praise/get_obj?", body, (res) => {
                    if (res.result && res.result.obj) {
                        // 已有记录，切换status值
                        var praise = res.result.obj;
                        var newStatus = praise.status === 1 ? 0 : 1;
                        
                        // 更新status值
                        this.$post("~/api/praise/set?praise_id=" + praise.praise_id, {
                            status: newStatus
                        }, (res) => {
                            if (res.result) {
                                _this.check_praised = newStatus === 1;
                                // 更新点赞数
                                if (newStatus === 1) {
                                    _this.obj.praise_len += 1;
                                } else {
                                    _this.obj.praise_len = Math.max(0, _this.obj.praise_len - 1);
                                }
                                var praise_len = _this.obj.praise_len;
                                this.$post('~/api/article/set?article_id=' + _this.obj["article_id"], {
                                    praise_len
                                }, (res) => {
                                    if(res.result){
                                        console.log("更新点赞数状态：" ,res.result);
                                    }
                                });
                                _this.$toast(newStatus === 1 ? _this.t('likeSuccess') : _this.t('cancelLike'));
                            } else if (res.error) {
                                _this.$toast(res.error.message);
                                console.error(res.error);
                            }
                        });
                    } else {
                        // 没有记录，创建新记录，status=1
                        body.status = 1;
                        this.$post("~/api/praise/add?", body, (res) => {
                            if (res.result) {
                                _this.check_praised = true;
                                _this.obj.praise_len += 1;
                                var praise_len = _this.obj.praise_len;
                                this.$post('~/api/article/set?article_id=' + _this.obj["article_id"], {
                                    praise_len
                                }, (res) => {
                                    if(res.result){
                                        console.log("添加点赞数状态：" ,res.result);
                                    }
                                });
                                _this.$toast(_this.t('likeSuccess'));
                            } else if (res.error) {
                                _this.$toast(res.error.message);
                                console.error(res.error);
                            }
                        });
                    }
                });
            },
            /**
             * 添加收藏
             */
            add_collect() {
                var {title, img, article_id} = this.obj;
                // 解析双语标题，使用当前语言显示
                var displayTitle = this.$getBilingualText(title);
                var body = {
                    title: displayTitle,
                    img,
                    source_table: "article",
                    source_field: "article_id",
                    source_id: article_id,
                    user_id: this.$store.state.user.user_id,
                };
                if (!this.check_collected) {
                    this.check_collected = true;
                    this.$post("~/api/collect/add?", body, (res) => {
                        this.$toast(this.t('collectSuccess'));
                    });
                } else {
                    this.check_collected = false;
                    this.$get("~/api/collect/del",
                        {
                            user_id: this.$store.state.user.user_id,
                            source_id: article_id,
                        }, (res) => {
                            this.$toast(this.t('cancelCollect'));
                        });
                }
            },
            check_collect() {
                var user_id = this.$store.state.user.user_id;
                var article_id = this.obj.article_id;
                this.$get('~/api/collect/count?', {
                    user_id,
                    source_table: "article",
                    source_field: "article_id",
                    source_id: article_id
                }, (res) => {
                    this.check_collected = res.result
                });
            }
        },
        mounted() {
            setTimeout(() => {
                this.check_collect();
                this.get_praise();
            }, 1000);
        }
    };
</script>

<style scoped>
    .ellipsis_1 {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
    }

    div {
        user-select: none;
    }

    .div_article {
        padding: 1.5rem 1rem;
    }

    .aside {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        margin: 0 0.625rem 0.625rem 0;
        font-size: 0.875rem;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        color: rgba(0, 0, 0, 0.3);
    }

    .aside_row {
        height: 2rem;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    aside_2 {
        display: flex;
        flex-direction: column;
    }

    .source {
        color: #576b95;
        margin: 0 0.2rem;
    }

    .tag {
        display: flex;
        align-items: center;
        padding: 0 0.25rem;
        font-size: 0.75rem;
        border-radius: 0.125rem;
        background: rgba(0, 0, 0, 0.05);
        color: rgba(0, 0, 0, 0.3);
    }


    .title {
        font-size: 1.35rem;
        line-height: 1.4;
        margin-bottom: 1rem;
        font-weight: 400;
    }

    .time {
        position: relative;
        top: 0.125rem;
    }

    .description {
        margin-bottom: 1rem;
        color: #292828;
    }

    .div_article .see {
        margin-left: 1rem;
    }

    .div_article .time {
        color: #999;
    }

    .btns_interact {
        height: 4rem;
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }

    .btns_interact button {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    @media (max-width: 576px) {
        ::v-deep .content img {
          width: 100%;
          height: 100%;
        }
    }

</style>
